package org.tom.org.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.tom.basic.exception.MyException;
import org.tom.basic.service.impl.BaseServiceImpl;
import org.tom.basic.util.MD5Utils;
import org.tom.basic.util.PageList;
import org.tom.basic.util.StrUtils;
import org.tom.org.domain.Employee;
import org.tom.org.domain.Shop;
import org.tom.org.mapper.EmployeeMapper;
import org.tom.org.mapper.ShopMapper;
import org.tom.org.query.ShopQuery;
import org.tom.org.service.IShopService;
import org.tom.org.util.Employee2Logininfo;
import org.tom.user.constant.UserConstant;
import org.tom.user.domain.Logininfo;
import org.tom.user.mapper.LogininfoMapper;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;



    /* 查询部门树，也就是从没有上级部门的 */
    @Override
    public List<Shop> loadTree() {
        return shopMapper.loadTree();
    }

    @Override
    public void shopRegister(Shop shop) {
//        判断两次密码是否一致
        Employee admin = shop.getAdmin();
        if (!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new MyException("两次密码不一致");
        }
//                判断用户名是否存在，用户名还可能是电话邮箱，需要在mapper层判断
        Employee employee = employeeMapper.findByUser(admin.getUsername());
        if (employee != null){
            throw new MyException("用户名存在");
        }

        // 将填入的密码加盐加密
        String salt = StrUtils.getComplexRandomString(32);
        String password = MD5Utils.encrypByMd5(salt + admin.getPassword());
        admin.setSalt(salt);
        admin.setPassword(password);
        // 调用方法将employee中的数据传到logininfo中
        Logininfo logininfo = Employee2Logininfo.emp2Logininfo(admin);
        // 将logininfo对象存入数据库中返回自增的主键
        logininfoMapper.add(logininfo);
        // 将返回的对象存入employee对象中应为在xml中对象Logininfo_id中是通过logininfo.id获取的
        admin.setLogininfo(logininfo);

//        两张先添加employee，
//        返回自增主键
        employeeMapper.add(admin);
//        将employee的自增id设置到shop中添加shop
        shop.setAdmin(admin);
        shopMapper.add(shop);


//        更新employee表中的shop_id
          admin.setShop_id(shop.getId()); // 在对象中shop_id也赋值但是修改不使用shop_id修改而是使用shop这个对象修改

        Shop shop_Admin = new Shop(); //  shop中使用对象接收
        shop_Admin.setId(shop.getId()); // 将shop中的id设置到对象之中
        admin.setShop(shop_Admin); // 将对象设置到admin中


        employeeMapper.update(admin);

    }


}
